package edu.upc.cineveinte.repository.jdbc;

import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.sql.Statement;
import java.util.ArrayList;
import java.util.List;

import org.springframework.dao.EmptyResultDataAccessException;

import edu.upc.cineveinte.domain.Pelicula;
import edu.upc.cineveinte.repository.PeliculaRepository;

public class PeliculaRepositoryJdbc
// extends JdbcDaoSupport
		implements PeliculaRepository {
	//
	// public PeliculaRepositoryJdbc(DataSource dataSource){
	// setDataSource(dataSource);
	// }

	public List<Pelicula> obtenerTodasPeliculas() throws SQLException {
		List<Pelicula> peliculas = new ArrayList<Pelicula>();
		String sql = "select * from pelicula";
		String url = "jdbc:mysql://localhost:3306/cineveinte?"
			+ "user=root&password=root";
		Connection conn = null;
		PreparedStatement ps = null;
		ResultSet rs = null;		
		try {
			Class.forName("com.mysql.jdbc.Driver");
			conn = DriverManager.getConnection(url);
			ps = conn.prepareStatement(sql);
			rs = ps.executeQuery(sql);
			while (rs.next()){
				Pelicula p = new Pelicula();
				p.setCodigo(rs.getInt("codigo"));
				p.setNombre(rs.getString("nombre"));
				p.setCartelera(rs.getBoolean("cartelera"));
				p.setEstreno(rs.getBoolean("estreno"));
				peliculas.add(p);
			}		
		}
		catch (Exception except) {
			SQLException ex = new SQLException(
				"Error Establishing Connection: " +
				except.getMessage());
			throw ex;
		}finally{
			if (rs != null) {
				try {
					// Close to prevent database cursor exhaustion
					rs.close();
				} catch (SQLException ex) {
				}
			}
			if (ps != null) {
				try {
					// Close to prevent database cursor exhaustion
					ps.close();
				} catch (SQLException ex) {
				}
			}	
			if (conn != null) {
				try {
					// Close to prevent database connection exhaustion
					conn.close();
				} catch (SQLException ex) {
				}
			}			
		}
		return peliculas;
	}
	
	/**
	 * Advances a ResultSet to the next row and throws an exception if there are no rows.
	 * @param rs the ResultSet to advance
	 * @throws EmptyResultDataAccessException if there is no next row
	 * @throws SQLException
	 */
//	private void advanceToNextRow(ResultSet rs) throws EmptyResultDataAccessException, SQLException {
//		if (!rs.next()) {
//			throw new EmptyResultDataAccessException(1);
//		}
//	}	
	// private class PeliculaRowMapper implements
	// ParameterizedRowMapper<Pelicula>{
	//
	// @Override
	// public Pelicula mapRow(ResultSet rs, int rowNum) throws SQLException {
	// Pelicula pelicula = new Pelicula();
	// pelicula.setCodigo(rs.getInt("codigo"));
	// pelicula.setNombre(rs.getString("nombre"));
	// pelicula.setEstreno(rs.getBoolean("estreno"));
	// pelicula.setCartelera(rs.getBoolean("cartelera"));
	// return pelicula;
	// }
	//
	// }

}
